// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build ignore

package main

import (
	"log"
	"time"
	"errors"
	"encoding/json"
	"net/url"
	"flag"
	"fmt"
	"github.com/gorilla/websocket"
)

// type Response struct {
// 	Code      int  `json:"code"`
// 	Message string   `json:"message"`
// 	Type int `json:"type"`
// 	To int `json:"to"`
// 	Uid int `json:"uid"`
// }

var (
	WriteResp = make(chan []byte)
)
func ConnClient() {
	var addr = flag.String("addr", "127.0.0.1:18301", "http service address")
	fmt.Println(addr)
	u := url.URL{Scheme: "ws", Host: *addr, Path: "/ws"}
	log.Printf("connecting to %s", u.String())
	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()
	//bind uid=0
	BindErr := c.WriteMessage(websocket.TextMessage, []byte("{\"code\":1,\"message\":\"bind\",\"uid\":0}"))
	if BindErr != nil {
		log.Println("write:", err)
		return
	}
	done := make(chan int)
	
	go func() {
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}
			log.Printf("recv: %s", message)
		}
	}()

	ticker := time.NewTicker(time.Second * 50)
	defer ticker.Stop()

	for {
		select {
		case <-done:
			return
		case message := <-WriteResp:
			err := c.WriteMessage(websocket.TextMessage, message)
			if err != nil {
				log.Println("write:", err)
				return
			}
		case t := <-ticker.C:
			// fmt.Println(t.String())
			err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
			if err != nil {
				log.Println("write:", err)
				return
			}
		}
	}
}
func Send(msg *Response) error {
	if msg.Code == 0 {
		return errors.New("Code is empty")
	}
	data, jsonErr := json.Marshal(msg)
	if jsonErr != nil {
		return jsonErr
	}
	fmt.Println("sending",msg, data)
	WriteResp <- data
	fmt.Println("sended")
	return nil
}